import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        self.filename = ".\\watchfile.txt"
        if event.src_path == self.filename :  # 监控指定文件内容、权限等变化
            print(">>>log file %s changed!" % event.src_path)
            self.outfileline()
        # print(event)

    def outfileline(self):
        file = open(self.filename, "r")
        content = file.read()
        file.close()

        lines = content.split("\n")  # 分隔符为换行符
        outlines = []
        for i,line in enumerate(lines):
            outlines.append(str(i+1)+". "+line)

        outlines = outlines[-1000:]
        outlines.reverse()
        reverse_content = "\n".join(outlines)
        print("====================================\n")
        print(reverse_content)

if __name__ == "__main__":
    # logging.basicConfig(level=logging.INFO, format='%(asctime)s -%(message)s', datefmt='%Y-%m-%d%H:%M:%S')

    path = '.'
    if len(sys.argv) > 1:
        path = sys.argv[1]

    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
